package com.tensquare.qa.controller;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.ribbon.proxy.annotation.Hystrix;
import com.tensquare.qa.client.LabelClient;
import com.tensquare.qa.pojo.Label;
import com.tensquare.qa.pojo.Problem;
import com.tensquare.qa.service.QaService;
import entity.PageResult;
import entity.Result;
import entity.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;


import java.util.List;

/**
 * Created by WF on 2020/10/20 10:49
 */
@RestController
@RequestMapping("problem")
public class QaController {
    @Autowired
    private QaService qaService;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private LabelClient labelClient;

    public static final String URL = "http://TENSQUARE-BASE" ;       //定义要访问的微服务的名称
    //1.查询最新问题列表
    @GetMapping("newlist/{id}/{page}/{size}")
    public Result newList(@PathVariable String id, @PathVariable int page, @PathVariable int size){
        //1.1)查询最新问题
        PageResult<Problem> pageResult= qaService.newList(id,page,size);
        //1.2)返回
        return new Result(StatusCode.OK,true,"查询最新问题列表成功！",pageResult);
    }

    //2.查询热门回答问题列表
    @GetMapping("hotlist/{id}/{page}/{size}")
    public Result hotlist(@PathVariable String id,@PathVariable int page,@PathVariable int size){
        //2.1)查询热门回答问题列表
        PageResult<Problem> pageResult= qaService.hotlist(id,page,size);

        //2.2)返回
        return new Result(StatusCode.OK,true,"查询热门回答问题列表成功！",pageResult);
    }
    
    //3.查询所有label标签列表(原生的服务调用：需要RestTempalate结合@LoadBanlanced)
    @GetMapping("/label/list")
    public Result findLabels(){
        List<Label> list = restTemplate.getForEntity(URL + "/label", List.class).getBody();
        return new Result(StatusCode.OK,true,"查询标签列表",list);
    }

    //4.根据id查询标签(使用OpenFeign组件实现服务调用)
    @GetMapping("/label/{labelId}")
    public Result findById(@PathVariable String labelId){
        return labelClient.findById(labelId);
    }


    //5.熔断器的方案二：使用restTemplate+@HystrixCommand命令完成熔断服务
    @GetMapping("/label/findAll")
    @HystrixCommand(fallbackMethod = "findLabelsFail")  //使用此注解完成熔断的功能
    public Result findLabels2(){
        List<Label> list = restTemplate.getForEntity(URL + "/label", List.class).getBody();
        return new Result(StatusCode.OK,true,"查询标签列表",list);
    }
    //熔断时调用的方法
    public Result findLabelsFail(){
        return new Result(StatusCode.ERROR,false,"熔断器开始工作了【RestTemplate+@HystrixCommand版本】");
    }

}
